"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""

class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next

class Solution:
    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
        if root is None:
            return None

        line = [root]
        while line:
            for idx in range(0, len(line) - 1):
                line[idx].next = line[idx + 1]
            temp = []
            for node in line:
                if node.left:
                    temp.append(node.left)
                if node.right:
                    temp.append(node.right)
            line = temp
        return root
